#########################################################################
# Function for ACDE for Subgroup Analysis

g.ACDE.fun <- function(data){ 
  
  ACDE <- matrix(NA, 10000, 5)
  
  for(i in 1:5){
    for(s in 1:10000){ 
      
      first <- lm(rel_feel ~ I(liberal-i)*rel_banperm + fem + age + edu_high + religiosity + leftright + rel_muslim + rel_dev + rel_rad + rel_immigrant, data=data)
      first.sim <- sim(first, 1)
      
      demediate <- coef(first.sim)[,2]%*%t(as.vector((data$liberal-i))) + coef(first.sim)[,11]%*%t(as.vector((data$liberal-i)*(data$rel_banperm))) 
      
      direct <- lm( I(rel_feel - t(demediate)) ~ rel_banperm  + fem + age + edu_high + religiosity + leftright + rel_muslim + rel_dev + rel_rad + rel_immigrant, data=data)
      direct.sim <- sim(direct, 1)
      
      ACDE[s,i] <- coef(direct.sim)[2]
      
    }
  } 
  return(ACDE)
}
